﻿using System.IO;
using Framework.Core.Io;
using Framework.Core.Process;
using Framework.Core.Process.Tasks;
using Rhino.Mocks;
using Xunit;

namespace Framework.Tests.Core.Process.Tasks
{
    public class HandleTest
    {
        private readonly MockRepository mockRepository = new MockRepository();
        private readonly IProcessRunner processRunnerMock;

        public HandleTest()
        {
            processRunnerMock = mockRepository.StrictMock<IProcessRunner>();
        }

        [Fact]
        public void Should_throw_if_handle_raise_error()
        {
            var handle = new Handle(@"d:\tutu");

            processRunnerMock
                .Expect(x => x.Start(handle))
                .Return(new ProcessResult(0, "blablabla Initialization Error \r\tblablabla", string.Empty, false));

            mockRepository.ReplayAll();
            Assert.Throws<ProcessResultException>(() => handle.Execute(processRunnerMock));
            mockRepository.VerifyAll();
        }

        [Fact]
        public void Should_validate_command()
        {
            var handleExe = new Handle(@"c:\temp\");

            const string path = @"handle.exe";
            Assert.True(File.Exists(path));
            Assert.Equal("handle", handleExe.Name);
            Assert.Equal(path, handleExe.FileName);
            Assert.Equal(@"-accepteula c:\temp\", handleExe.Arguments);
            Assert.False(handleExe.IsNative);

            const string output = @"
Handle v3.42
Copyright (C) 1997-2008 Mark Russinovich
Sysinternals - www.sysinternals.com
RTSApp.exe         pid: 7420      C: D:\_Tools\Royal TS
RTSApp.exe         pid: 7420    248: D:\_Tools\Royal TS\AxInterop.MSTSCLib.dll
RTSApp.exe         pid: 7420    2F0: D:\_Tools\Royal TS\Interop.MSTSCLib.dll
toto.exe           pid: 13      2F0: D:\_Tools\Royal TS\Interop.MSTSCLib.dll
";


            var o = new[] { GetProcessResult("RTSApp.exe", 7420), GetProcessResult("toto.exe", 13) };
            processRunnerMock.Expect(x => x.Start(new TaskList()))
                .Return(new ProcessResult(0, string.Join(System.Environment.NewLine, o), string.Empty, false));
            processRunnerMock.Expect(x => x.Start(handleExe)).Return(new ProcessResult(0, output, string.Empty, false));

            mockRepository.ReplayAll();
            Assert.NotEmpty(handleExe.Execute(processRunnerMock));
            mockRepository.VerifyAll();
        }

        private static string GetProcessResult(string service, int pid)
        {
            return string.Format(@"{0}		{1}	{2}	C:\Windows\system32\mmc.exe	C:\Windows\system32\mmc.exe 3121456", Path.GetFileNameWithoutExtension(service), pid, service);
        }
    }
}